package com.dhcc.nurtv;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @author:gaoruishan
 * @date:202021/9/16/14:21
 * @email:grs0515@163.com
 */
public class WebUtil {
    // public static final String WEB_URL = "file:///android_asset/index.html";
    public static final String WEB_URL = "http://172.22.31.47/dthealth/web/scripts/nurse/nurtv/index.html";
    public static final String URL = "URL";
    public static final String EXTRAS = "extras";

    public static final String EVENT_TOAST = "toast";
    public static final String EVENT_LOADING = "loading";
    public static final String EVENT_DIALOG = "dialog";
    public static final String SHOW = "show";
    public static final String FAIL = "fail";
    private static final String TAG = "WebUtil";

    private static Handler deliver = new Handler(Looper.getMainLooper());

    public static void init(Activity activity, LinearLayout linearLayout, String url) {
        WebView webView = new WebView(activity);
        linearLayout.addView(webView);
        setWebSetting(webView,null);
        // 加载asset文件夹中html的格式
//        webView.loadUrl("file:///android_asset/demo1.html");
        webView.loadUrl(url);
    }

    public static void init(WebView webview,String url) {
        setWebViewSSl(webview);

        setWebSetting(webview, null);
        Log.e(TAG,"(WebUtil.java:214) "+url);
        //不可编辑
        webview.requestFocus(View.FOCUS_DOWN);
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_UP:
                        if (!v.hasFocus()) {
                            v.requestFocus();
                        }
                        break;
                }
                return false;
            }
        });
        webview.loadUrl(url);

    }
    /**
     * Js和Web交互
     */
    public static class JsInterface {

        public static final String REQUEST = "request";
        public static final String CONFIG = "config";

        @JavascriptInterface
        public void callAndroid(String content, String type) {
//            Toast.makeText(, "测试", Toast.LENGTH_SHORT).show();
            Log.e("TAG","(JsInterface.java:292)  type= " + type + " ,content=  " + content);
            String finalType = type.toUpperCase();
            deliver.post(new Runnable() {
                @Override
                public void run() {
                    //请求
                    if (finalType.equalsIgnoreCase(REQUEST)) {
                        onCallRequest(content, finalType);
                        return;
                    }
                    //配置
                    if (finalType.equalsIgnoreCase(CONFIG)) {
                        initConfig(content, finalType);
                        return;
                    }
                    //事件
                    onCallEvents(content, finalType);
                }
            });

        }

        private void onCallEvents(String content, String type) {
            if (EVENT_TOAST.equalsIgnoreCase(type)) {
//                ToastUtils.showShort(content);
            }
//            if (EVENT_LOADING.equalsIgnoreCase(type)) {
//                boolean b = SHOW.equalsIgnoreCase(content);
//                loadingProgress.setVisibility(b ? View.VISIBLE : View.GONE);
//            }
            if (EVENT_DIALOG.equalsIgnoreCase(type)) {
//                if (content.contains(FAIL)) {
//                    CommDialog.showCommDialog(ActivityUtils.getTopActivity(), content, "", R.drawable.icon_popup_error_patient, null, true);
//                }
            }
        }

        private void initConfig(String content, String finalType) {

        }

        private void onCallRequest(String content, String finalType) {

        }
    }
    /**
     * 注入js
     * @param webview
     */
    protected static void addJavascriptInterfaceWebView(WebView webview) {
        webview.addJavascriptInterface(new JsInterface(), "JsInterface");
    }

    /**
     * 设置web属性
     * @param webview
     */
    public static void setWebSetting(WebView webview, WebViewClient client) {
        try {
            //本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = webview.getSettings().getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(webview.getSettings(), true);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "(WebUtil:163) setWebSetting:" + e.toString());
        }
        //支持js
        webview.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webview.getSettings().setSupportZoom(true);
        // 显示放大缩小
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setDisplayZoomControls(false);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        //取消滚动条白边效果
        webview.setWebChromeClient(new WebChromeClient());
        addJavascriptInterfaceWebView(webview);
//        ProgressBar progressBar = new ProgressBar()
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.e(TAG, "(WebUtil:180) shouldOverrideUrlLoading:" + request.getMethod() + "\n" + request.getUrl());
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG, "(WebUtil:186) shouldOverrideUrlLoading:" + url);
//                webview.loadUrl(url);
//                return true;
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.e(TAG, "(WebUtil:194) onPageStarted:" +url);
                super.onPageStarted(view, url, favicon);
                if (client != null) {
                    client.onPageStarted(view, url, favicon);
                }
            }

            @Override
            public void onPageFinished(WebView webView, String url) {
                Log.e(TAG, "(WebActivity.java:207) onPageFinished" + url);
                if (client != null) {
                    client.onPageFinished(webView, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);
                handler.proceed();//接受证书
            }
        });

        //设置默认为utf-8
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.getSettings().setBlockNetworkImage(false);
        //扩大比例的缩放
        webview.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);

        // 解决对某些标签的不支持出现白屏
        webview.getSettings().setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //注意安卓5.0以上的权限
            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }


    public static void setWebViewSSl(WebView webviewVitalsignchart) {
        //设置WebView支持JavaScript
        webviewVitalsignchart.getSettings().setJavaScriptEnabled(true);
        //不使用缓存
        webviewVitalsignchart.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //添加客户端支持
        webviewVitalsignchart.setWebChromeClient(new WebChromeClient());
        //设置WebView使用广泛的视窗
        webviewVitalsignchart.getSettings().setUseWideViewPort(true);
        //设置是否启用了DOM storage API。
        webviewVitalsignchart.getSettings().setDomStorageEnabled(true);
        //缩放
        webviewVitalsignchart.getSettings().setBuiltInZoomControls(false);
        webviewVitalsignchart.getSettings().setSupportZoom(false);
        //设置WebView使用广泛的视窗
        webviewVitalsignchart.getSettings().setLoadWithOverviewMode(true);
        //自动打开窗口
        webviewVitalsignchart.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    }

    public static void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("TLS");
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }

}
